(function (angular) {
  'use strict';

  angular.module('services.customActivity.realtime', [])
    .factory('activityList', activityList)
    .factory('activityManager', activityManager)
    .service('formControl', formControl)
    .service('previewEdited', function(){
      this.state = false;
    });

  function activityList($http) {
    return {
      activities: [],
      getList: getList,
      deleteActivity: deleteActivity
    };

    function getList(callback) {
      $http.get('/sas/customActivity/realTime/activityList/query')
        .success(function (res) {
          this.activities = res.data;
          if(callback){
            callback();
          }
        }.bind(this));
    }

    function deleteActivity(activityId) {
      $http.post('/sas/customActivity/realTime/activityList/delete', {activityId: activityId})
        .success(function () {
          this.getList();
        }.bind(this));
    }
  }

  function activityManager($http, formControl, MODULES_ID, previewEdited) {
    return {
      configModules: [],
      configure: {},
      displaySetting: {
        time: true,
        province: true
      },
      layout: [],
      activityInfo: {
        activityId: undefined,
        activityState: ''
      },
      getConfigModules: getConfigModules,
      saveActivity: saveActivity,
      getSavedConfig: getSavedConfig,
      setConfigure: setConfigure,
      resume: resume,
      reset: reset
    };

    function resume(){
      this.startTime = formControl.timeTransfor(this.configure.startTime);
      this.endTime = formControl.timeTransfor(this.configure.endTime);
      this.displaySetting.province = this.configure.displaySetting.province === '0';
      this.displaySetting.time = this.configure.displaySetting.time === '0';
    }

    function reset(){
      this.configModules = [];
      this.configure = {};
      this.displaySetting = {
        time: true,
        province: true
      };
      this.layout = [];
      this.startTime = undefined;
      this.endTime = undefined;
      this.activityInfo.activityId = undefined;
      this.activityInfo.activityState = '';
    }

    //应该要保证在页面加载前 执行 getConfigModules()
    function getConfigModules(callback) {
      $http.get('/sas/customActivity/realTime/configModules/query')
        .success(function (res) {
          this.configModules = res.data;
          if(callback){
            callback();
          }
        }.bind(this));
    }

    function saveActivity(activityId, callback) {
      var req;

      this.setConfigure();

      if (is.empty(this.configure.activityName) || is.undefined(this.configure.activityName)) {
        return alert('主题名称不能为空');
      }

      if(this.configure.activityName.length > 30){
        return alert('主题名称的长度不能大于30个字符');
      }

      if (is.empty(this.configure.provinceCode)) {
        return alert('必须选择一个省份');
      }

      if (is.empty(this.configure.selectedModules)) {
        return alert('必须选择一个模块');
      }


      if (angular.isDefined(activityId) && is.not.empty(activityId)) {
        req = angular.merge({activityId: activityId}, this.configure);
        $http.post('/sas/customActivity/realTime/activity/update', req)
          .success(function (res) {
            if (res.state !== '10000') {
              alert(res.message);
            } else {
              callback();
            }
          });
      } else {
        $http.post('/sas/customActivity/realTime/activity/save', this.configure)
          .success(function (res) {
            if (res.state !== '10000') {
              alert(res.message);
            } else {
              callback();
            }
          });
      }
    }

    function getSavedConfig(activityId, callback) {
      $http.post('/sas/customActivity/realTime/savedConfig/query', {activityId: activityId})
        .success(function (res) {
          this.configure = res.data;
          this.startTime = formControl.timeTransfor(res.data.startTime);
          this.endTime = formControl.timeTransfor(res.data.endTime);
          formControl.selectModule(this.configModules, this.configure.selectedModules);
          previewEdited.state = true;
          this.displaySetting.province = res.data.displaySetting.province === '0';
          this.displaySetting.time = res.data.displaySetting.time === '0';

          if(callback){
            callback();
          }
        }.bind(this));
    }

    function setConfigure() {
      var that = this;

      this.configure.selectedModules = formControl.getSelectedModuleId(this.configModules);
      this.configure.startTime = formControl.timeTransfor(this.startTime);
      this.configure.endTime = formControl.timeTransfor(this.endTime);
      this.configure.displaySetting = {
        time: this.displaySetting.time ? '0' : '1',
        province: this.displaySetting.province ? '0' : '1'
      };

      if(!previewEdited.state){
        that.layout = [];
        angular.forEach(MODULES_ID, function (busLines, moduleName) {
          var directiveName = moduleName.toLowerCase().replace(/\_/g, '-');
          directiveName = '<' + directiveName + ' selected-modules="activityManager.configure.selectedModules"></' + directiveName + '>';
          if (is.not.object(busLines) && that.configure.selectedModules.indexOf(busLines) !== -1) {
            that.layout.push(directiveName);
          }
          angular.forEach(busLines, function (code) {
            if (that.configure.selectedModules.indexOf(code) !== -1 &&
              that.layout.indexOf(directiveName) === -1) {
              that.layout.push(directiveName);
            }
          });
        });
        that.configure.layout = that.layout.join('');
      }
    }
  }

  function formControl(checkboxManager) {
    this.timeTransfor = function (time) {
      var timeCopy = angular.copy(time);
      if (typeof time === 'string') {
        return new Date(time);
      } else {
        timeCopy.setMinutes(timeCopy.getMinutes() - timeCopy.getTimezoneOffset());
        return timeCopy.toISOString().split('.')[0].replace('T', ' ');
      }
    };

    this.selectModule = function (modules, selected) {
      iterator(modules, function (item) {
        item.selected = false;

        if (angular.isDefined(selected) && angular.isArray(selected)) {
          selected.forEach(function (moduleId) {
            if (item.moduleId === moduleId) {
              item.selected = true;
            }
          });
        }
      });
      iterator(modules, function(item){
        if(item.moduleId !== 310 && item.childModule !== null){
          checkboxManager.selectChild(item);
        }
      });
    };

    this.getSelectedModuleId = function (modules) {
      var selectedModuleId = [];
      iterator(modules, function (item) {
        if ((item.childModule === null || item.childModule.length === 0) && item.selected) {
          selectedModuleId.push(item.moduleId);
        }
      });

      return selectedModuleId;
    };

    function iterator(arr, callback) {
      angular.forEach(arr, function (item, index) {
        callback(item, index);
        if (item.childModule !== null) {
          iterator(item.childModule, callback);
        }
      });
    }
  }
})(angular);